; To find the square root is to find the fixed point
; f(x) = x

(define (average a b)
    (/ (+ a b) 2.0))

(define (sqrt2 x)
    (fixed-point (lambda (y) (average (/ x y) y))
    1))

(define (fixed-point f start)
    (define tolerance 0.00001)
    (define (close-enuf? u v)
        (< (abs (- u v)) tolerance))
    (define (iter old new)
        (display new)
        (newline)
        (if (close-enuf? old new)
        new
        (iter new (f new))))
    (iter start (f start)))

(sqrt2 2)

; Average damping method

(define (sqrt3 x)
  (fixed-point (average-damp (lambda(y) (/ x y)))
   1))

(define (average-damp f)
    (lambda (x) (average (f x) x))
)

(sqrt3 2)

; General Newton method

(define (sqrt4 x)
    (newton (lambda (y)
        (- x (square y)))
    1))

(define (newton f guess)
    (define dx 0.000001)
    (define df (deriv f))
    (fixed-point (lambda (x) 
                    (- x (/ (f x) (df x))))
    guess))

; (define (deriv g)
;     (define dx 0.000001)
; 	(lambda (x)
; 		(/ (- (g (+ x dx)) (g x)) dx)))

(define deriv
    (lambda (f)
    (lambda (x)
        (/ (- (f (+ x dx)) (f x))
         dx))))

(define dx 0.000001)

(sqrt4 2)